<?php

namespace app\mini\controller\salesman;

use app\common\controller\ApiController;
use app\common\enum\order\GoodsType;
use app\common\enum\Status;
use app\common\model\DealerGoods;
use app\common\model\GoodsCate as GoodsCateModel;
use app\common\model\SalesmanDealer;
use app\common\model\DealerGoodsCate;
use app\mini\model\Cart;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\common\service\CategoryService;
use app\common\traits\SearchTrait;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * @ControllerAnnotation (title="商品相关")
 */

class Goods extends ApiController
{
    use SearchTrait;

    private array $dealer_ids;
    private GoodsCateModel $cate_model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new DealerGoods();
        $this->cate_model = new GoodsCateModel();
        // 获取业务员对应的经销商ID
        $this->dealer_ids = (new SalesmanDealer)->where('salesman_id', $this->userInfo['id'])->column('dealer_id');
    }

    /**
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function dealerCateList(): Json
    {
        $list = $this->cate_model->field('id,pid,name')
                                 ->where('status', Status::NORMAL)->select();
        return $this->success((new CategoryService())->getTreeData($list));
    }

    /**
     * @return Json
     * @throws DbException
     * TODO 1、兼容车销需要传仓库id；2、分类目前集团维护，不能使用经销商分类
     */
    public function list(): Json
    {
        $get = $this->request->get();
        if(empty($get['store_id'])){
            return $this->error('门店参数缺失！');
        }
        $sql = $this->model->with('spec');
        if(!empty($get['dealer_cate_id'])){
            $sql = $sql->where('dealer_cate_id', $get['dealer_cate_id']);
        }
        if(!empty($get['name'])){
            $sql = $sql->where('name', 'like','%'.$get['name'].'%');
        }
        // 获取经销商的商品列表
        $list = $sql->whereIn('dealer_id', $this->dealer_ids)->where('status',1)->paginate($get['limit']??15)->each(function ($item) use ($get) {
            $cartList = Cart::field('num,unit,goods_type,dealer_goods_spec_id,remark')
                            ->where('store_id',$get['store_id'])
                            ->where('salesman_id',$this->uid)
                            ->where('goods_type','in',[1,2])
                            ->where('dealer_goods_id',$item->id)
                            ->where('company_warehouse_id', $get['warehouse_id'])
                            ->order('goods_type asc')->select();
            $desc = '';
            foreach ($cartList as $cart){
                if ($cart['goods_type'] == GoodsType::GIFT){
                    $desc .= '赠'.$cart['num'].$cart['unit'].',';
                }else{
                    $desc .= $cart['num'].$cart['unit'].',';
                }
            }
//            $cartBySpec = array_column($cartList->toArray(),null,'dealer_goods_spec_id');
            $specPrice = '';
            $specArr = $item->spec->toArray();
            $item->spec_name = implode(',',array_column($specArr,'name'));
            array_multisort(array_column($specArr,'sale_price'),SORT_ASC,$specArr);
            foreach ($specArr as $spec){
                $specPrice .= '￥'.$spec['sale_price'].',';
//                $spec['cart_num'] = $cartBySpec[$spec['id']]['num'];
            }
            usort($specArr, function ($a, $b) {
                return $b['ratio'] <=> $a['ratio'];  // 使用太空船操作符进行升序排序
            });
            $sales_stock = $item->sales_stock;
            $stockArray = [];
            foreach ($specArr as $spec){
                $stockArray[$spec['id']] = intdiv($sales_stock,$spec['ratio']);
                $sales_stock = $sales_stock % $spec['ratio'];
            }
            $item->cart_desc = $desc;
            $item->spec_price = $specPrice;
            $item->spec->each(function ($spec) use ($get,$stockArray){
                $spec->stock = $stockArray[$spec->id];
                $spec->remark = Cart::where('store_id',$get['store_id'])
                    ->where('salesman_id',$this->uid)->where('dealer_goods_spec_id',$spec->id)->value('remark')??'';
            });
        })->toArray();
        $list['total_num'] = Cart::where([['store_id', '=', $get['store_id']],['salesman_id', '=', $this->uid],['goods_type','in',[1,2]]])->sum('num');
        return $this->success($list);
    }

    /**
     * @return Json
     * @throws DbException
     */
    public function returnList(): Json
    {
        $get = $this->request->get();
        if(empty($get['store_id'])){
            return $this->error('门店参数缺失！');
        }
        $sql = $this->model->with('spec');
        if(!empty($get['dealer_cate_id'])){
            $sql = $sql->where('dealer_cate_id', $get['dealer_cate_id']);
        }
        if(!empty($get['name'])){
            $sql = $sql->where('name', 'like','%'.$get['name'].'%');
        }
        // 获取经销商的商品列表
        $list = $sql->whereIn('dealer_id', $this->dealer_ids)->where('status',1)->paginate($get['limit']??15)->each(function ($item) use ($get) {
            $cartList = Cart::field('num,unit,goods_type,dealer_goods_spec_id')->where('store_id',$get['store_id'])
                ->where('salesman_id',$this->uid)->where('goods_type',3)->where('company_warehouse_id', $get['warehouse_id'])
                ->where('dealer_goods_id',$item->id)->order('goods_type asc')->select();
            $desc = '退';
            foreach ($cartList as $cart){
                $desc .= $cart['num'].$cart['unit'].',';
            }
            $specPrice = '';
            $specArr = $item->spec->toArray();
            $item->spec_name = implode(',',array_column($specArr,'name'));
            array_multisort(array_column($specArr,'sale_price'),SORT_ASC,$specArr);
            foreach ($specArr as $spec){
                $specPrice .= '￥'.$spec['sale_price'].',';
            }
            usort($specArr, function ($a, $b) {
                return $b['ratio'] <=> $a['ratio'];  // 使用太空船操作符进行升序排序
            });
            $sales_stock = $item->sales_stock;
            $stockArray = [];
            foreach ($specArr as $spec){
                $stockArray[$spec['id']] = intdiv($sales_stock,$spec['ratio']);
                $sales_stock = $sales_stock % $spec['ratio'];
            }
            $item->cart_desc = $desc;
            $item->spec_price = $specPrice;
            $item->spec->each(function ($spec) use ($get,$stockArray){
                $spec->stock = $stockArray[$spec->id];
                $spec->remark = Cart::where('store_id',$get['store_id'])
                    ->where('salesman_id',$this->uid)->where('dealer_goods_spec_id',$spec->id)->value('remark')??'';
            });
        })->toArray();
        $list['total_num'] = Cart::where([['store_id', '=', $get['store_id']],['salesman_id', '=', $this->uid],['goods_type','=',3]])->sum('num');
        return $this->success($list);
    }
}